<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;

class Consumer extends Authenticatable
{
    protected $guarded = [];

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'update_time';

    //获取微信用户
    public function get_wechat_users($query){
        $where = [];

        if($query->company_id){
            $where[] = ['company_id',$query->company_id];
        }

        if($query->phone){
            $where[] = ['phone',$query->phone];
        }
        if(isset($query->user_status)){
            $where[] = ['user_status',$query->user_status];
        }
        if($query->register_start){
            $where[] = ['consumers.create_time','>=',$query->register_start];
        }
        if($query->register_end){
            $where[] = ['consumers.create_time','<=',$query->register_start];
        }

        if($query->username){
            $where[] = ['username',$query->username];
        }
        if(isset($query->has_manager)){
            if($query->has_manager == 0){//没有服务经理
                $where[] = ['manager_id',null];
            }elseif($query->has_manager == 1){//有服务经理
                $where[] = ['manager_id','!=',null];
            }
        }
        if($query->manager_id){
            $where[] = ['manager_id',$query->manager_id];
        }

        return $this->join('consumer_infos','consumers.id','consumer_infos.cid')
                        ->leftJoin('companies','consumer_infos.company_id','companies.id')->where($where)
                        ->select('consumers.id','consumers.phone','username','manager_name','consumers.create_time','user_status','company_name')
                        ->orderBy('consumers.create_time','desc')->paginate();
    }


    //冻结微信用户、解冻用户
    function frozen_user($user_id,$user_status){
        $data = ['user_status'=>$user_status];
        return $this->update_user($user_id,$data);
    }

    //重置密码
    function reset_password($user_id){
        $phone = $this->find($user_id)->value('phone');

        //新密码为手机号后6位
        $new_password = substr($phone,-6);
        $data = ['password'=>bcrypt($new_password)];

        return $this->update_user($user_id,$data);
    }

    //修改用户信息
    function update_user($user_id,$data){
        return $this->where('id',$user_id)->update($data);
    }


    public function info()
    {
        return $this->hasOne(ConsumerInfo::class,'cid');
    }





}
